import React, { useRef, useState } from "react";
import { MyNavBar, ProFileInput, ProFilePicker } from "../../../../components";
import style from "./style.module.scss";
import addIcon from "../../../../assets/images/image/hdpi/add.png";
import closeIcon from "../../../../assets/images/icon/common resource/hdpi/common_icon_close_n.png";
import { useLocation, useNavigate, useSearchParams } from "react-router-dom";
import {
  addProFile,
  getProFile,
  updateProFile,
  uploadArchivesPicture,
} from "../../../../api/my";
import { useAppSelector } from "../../../../store/hooks";
import { Toast, DatetimePicker, PickerPopupActions } from "react-vant";

//  proFileInput 返回参数类型
interface valueRawState {
  type: string;
  val: string;
}

//  我的档案（添加-编辑） input数据类型
interface ProFileRawState {
  labelText?: string;
  tooltip: string;
  value: string;
}

//  我的档案（添加-编辑） picker数据类型
interface PickerRawState {
  type: string;
  tooltip: string;
  dateTime: string;
  actions?: PickerPopupActions;
}

//  我的档案（添加-编辑） 相关图片数据类型
interface RelatedImages {
  relatedImageUrl: string;
}

//  我的档案（添加-编辑） 档案数据类型
interface myProFileRawState {
  diseaseBefore: string;
  diseaseMain: string;
  diseaseNow: string;
  archivesId: number;
  picture: string;
  treatmentEndTime: number;
  treatmentHospitalRecent: string;
  treatmentProcess: string;
  treatmentStartTime: number;
  userId: number;
}

const Index: React.FC = () => {
  const navigate = useNavigate();
  //  用于图片上传的 input Ref
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [value, setValue] = React.useState(new Date());
  //  用于接收用户档案参数  archivesId (添加)
  const [id, setId] = useState<number>(NaN);
  const [type, setType] = useState<string>("");
  const [searchParams] = useSearchParams();
  //  获取用户档案参数  (编辑)
  const archivesId = Number(searchParams.get("archivesId"));
  const { state } = useLocation();
  const proFile = state;
  const userId = useAppSelector((state) => state.user.userInfo.userId);
  const sessionId = useAppSelector((state) => state.user.userInfo.sessionId);
  //  存放用户自己的档案 数据
  const [myProFile, setMyProFile] = useState<myProFileRawState>(
    proFile || {
      diseaseBefore: "",
      diseaseMain: "",
      diseaseNow: "",
      treatmentEndTime: "",
      treatmentHospitalRecent: "",
      treatmentProcess: "",
      treatmentStartTime: "",
    }
  );
  //  我的档案（添加-编辑） input数据
  const [proFileList, setProFileList] = useState<ProFileRawState[]>([
    {
      labelText: "[主要症状]",
      tooltip: "请输入您的主要症状",
      value: myProFile.diseaseMain,
    },
    {
      labelText: "[现病史]",
      tooltip: "请详细输入您的当前病状",
      value: myProFile.diseaseNow,
    },
    {
      labelText: "[既往病史]",
      tooltip: "请输入您的既往病史",
      value: myProFile.diseaseBefore,
    },
    {
      labelText: proFile ? "[治疗经历]" : "[最近一次治疗经历]",
      tooltip: "请输入医院名称",
      value: myProFile.treatmentHospitalRecent,
    },
  ]);
  //  我的档案（添加-编辑） picker数据
  const [pickerList, setPickerList] = useState<PickerRawState[]>([
    {
      type: "start",
      tooltip: "请选择治疗开始时间",
      dateTime: "",
    },
    {
      type: "end",
      tooltip: "请选择治疗结束时间",
      dateTime: "",
    },
  ]);
  //  我的档案  相关图片数据  (添加)
  const [relatedImages, setRelatedImages] = useState<RelatedImages[]>([]);
  //  我的档案  相关图片数据  (编辑)
  const [relatedImages_edit, setRelatedImages_edit] = useState<RelatedImages[]>(
    [
      {
        relatedImageUrl: proFile?.picture || "",
      },
    ]
  );
  //  我的档案 input 内容修改函数
  const changeProFile = (value: valueRawState) => {
    let tempList;
    switch (value.type) {
      case "[主要症状]":
        setMyProFile({ ...myProFile, diseaseMain: value.val });
        tempList = JSON.parse(JSON.stringify(proFileList));
        tempList = tempList.map((item: ProFileRawState) => {
          if (item.labelText === value.type) {
            item.value = value.val;
          }
          return item;
        });
        setProFileList(tempList);
        return;
      case "[现病史]":
        setMyProFile({ ...myProFile, diseaseNow: value.val });
        tempList = JSON.parse(JSON.stringify(proFileList));
        tempList = tempList.map((item) => {
          if (item.labelText === value.type) {
            item.value = value.val;
          }
          return item;
        });
        setProFileList(tempList);
        return;
      case "[既往病史]":
        setMyProFile({ ...myProFile, diseaseBefore: value.val });
        tempList = JSON.parse(JSON.stringify(proFileList));
        tempList = tempList.map((item) => {
          if (item.labelText === value.type) {
            item.value = value.val;
          }
          return item;
        });
        setProFileList(tempList);
        return;
      case "[最近一次治疗经历]":
        setMyProFile({ ...myProFile, treatmentHospitalRecent: value.val });
        tempList = JSON.parse(JSON.stringify(proFileList));
        tempList = tempList.map((item) => {
          if (item.labelText === value.type) {
            item.value = value.val;
          }
          return item;
        });
        setProFileList(tempList);
        return;
      case "[治疗经历]":
        setMyProFile({ ...myProFile, treatmentHospitalRecent: value.val });
        tempList = JSON.parse(JSON.stringify(proFileList));
        tempList = tempList.map((item) => {
          if (item.labelText === value.type) {
            item.value = value.val;
          }
          return item;
        });
        setProFileList(tempList);
        return;
      case "other":
        setMyProFile({ ...myProFile, treatmentProcess: value.val });
    }
  };
  //  开启时间选择器函数
  const onOpen = (actions: PickerPopupActions, type: string) => {
    actions.open();
    setType(type);
  };
  //  我的档案 picker 内容修改函数
  const changePicker = (value: Date) => {
    setValue(value);
    let tempPickerList = JSON.parse(JSON.stringify(pickerList));
    tempPickerList = tempPickerList.map((item: PickerRawState) => {
      if (item.type === type) {
        item.dateTime = value.toLocaleDateString().split("/").join("-");
      }
      return item;
    });
    setPickerList(tempPickerList);
  };

  const changeStartTime = (value: Date) => {
    const tempPickerList = JSON.parse(JSON.stringify(pickerList));
    tempPickerList[0].dateTime = value
      .toLocaleDateString()
      .split("/")
      .join("-");
    setPickerList(tempPickerList);
  };

  const changeEndTime = (value: Date) => {
    const tempPickerList = JSON.parse(JSON.stringify(pickerList));
    tempPickerList[1].dateTime = value
      .toLocaleDateString()
      .split("/")
      .join("-");
    setPickerList(tempPickerList);
  };
  //  用户已选择图片处理函数
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const tar = e.target;
    if (tar.files) {
      const file = tar.files[0];
      const fr = new FileReader();
      fr.readAsDataURL(file);
      fr.onload = async (e: ProgressEvent<FileReader>) => {
        if (proFile) {
          handleUpload(file, id);
          let temp = [...relatedImages_edit];
          const url = e.target?.result as string;
          temp = temp.map((item) => ({ ...item, relatedImageUrl: url }));
          setRelatedImages_edit(temp);
        } else {
          handleUpload(file, id);
          const temp = [...relatedImages];
          const url = e.target?.result as string;
          temp.push({ relatedImageUrl: url });
          setRelatedImages(temp);
        }
      };
    }
  };
  //  上传用户档案相关图片  接口
  const handleUpload = async (file: File, id: number) => {
    const picture = file;
    await uploadArchivesPicture(id, archivesId, picture, userId, sessionId);
  };

  const uploadImages = async () => {
    if (fileInputRef.current) {
      fileInputRef.current.click();
    }
    if (!proFile) {
      await addProFile(pickerList, myProFile, userId, sessionId);
      const resp = await getProFile(userId, sessionId);
      setId(resp.result[0].archivesId);
    }
  };
  //  修改用户档案  接口
  const onSave = async () => {
    if (archivesId) {
      const resp = await updateProFile(
        pickerList,
        myProFile,
        archivesId,
        userId,
        sessionId
      );
      const { message, status } = resp;
      if (status === "0000") {
        Toast.success(message);
        navigate("/my/profile");
      }
    } else {
      navigate("/my/profile");
    }
  };

  return (
    <div className={style.operateProFile}>
      <input
        type="file"
        ref={fileInputRef}
        style={{ display: "none" }}
        onChange={(e) => handleChange(e)}
      />
      <div className="navbar">
        <MyNavBar
          title="我的档案"
          style={{ backgroundColor: "#fff" }}
          onClickLeft={() => {
            navigate("/my/profile?previousPath=/my");
          }}
        ></MyNavBar>
      </div>
      <div className={style.content}>
        {proFileList &&
          proFileList.map((item, index) => {
            return (
              <ProFileInput
                tooltip={item.tooltip}
                labelText={item.labelText}
                value={item.value}
                key={index}
                getValue={changeProFile}
              ></ProFileInput>
            );
          })}
        {!proFile ? (
          pickerList.map((item, index) => {
            return (
              <DatetimePicker
                popup={{
                  round: true,
                }}
                type="date"
                title="选择年月日"
                minDate={new Date(2021, 0, 1)}
                maxDate={new Date(2025, 10, 1)}
                value={value}
                onConfirm={(value: Date) => changePicker(value)}
                key={index}
              >
                {(val, _, actions: PickerPopupActions) => {
                  return (
                    <ProFilePicker
                      tooltip={item.tooltip}
                      type={item.type}
                      dateTime={item.dateTime}
                      actions={actions}
                      getTime={onOpen}
                    ></ProFilePicker>
                  );
                }}
              </DatetimePicker>
            );
          })
        ) : (
          <div className={style.time_wrapper}>
            <DatetimePicker
              popup={{
                round: true,
              }}
              type="date"
              title="选择年月日"
              minDate={new Date(2021, 0, 1)}
              maxDate={new Date(2025, 10, 1)}
              value={value}
              onConfirm={(value: Date) => changeStartTime(value)}
            >
              {(val, _, actions) => {
                return (
                  <div
                    className={style.startTime}
                    onClick={() => actions.open()}
                  >
                    {pickerList[0].dateTime !== ""
                      ? pickerList[0].dateTime
                      : myProFile.treatmentStartTime}
                  </div>
                );
              }}
            </DatetimePicker>
            <DatetimePicker
              popup={{
                round: true,
              }}
              type="date"
              title="选择年月日"
              minDate={new Date(2021, 0, 1)}
              maxDate={new Date(2025, 10, 1)}
              value={value}
              onConfirm={(value: Date) => changeEndTime(value)}
            >
              {(val, _, actions) => {
                return (
                  <div className={style.endTime} onClick={() => actions.open()}>
                    {pickerList[1].dateTime !== ""
                      ? pickerList[1].dateTime
                      : myProFile.treatmentEndTime}
                  </div>
                );
              }}
            </DatetimePicker>
          </div>
        )}
        <ProFileInput
          tooltip="请输入治疗过程"
          value={proFile?.treatmentProcess || ""}
          getValue={changeProFile}
        ></ProFileInput>
        {!proFile ? (
          <div className={style.relatedImages_wrapper}>
            <div className={style.relatedImages_title}>[相关图片]</div>
            <div className={style.attention}>
              最多可添加6张图片；长按为图片排序
            </div>
            <div>
              {relatedImages &&
                relatedImages.map((item, index) => {
                  return (
                    <img
                      src={item.relatedImageUrl}
                      alt=""
                      key={index}
                      className={style.relatedImage}
                    />
                  );
                })}
              <img
                src={addIcon}
                alt=""
                className={style.relatedImage}
                onClick={() => uploadImages()}
              />
            </div>
          </div>
        ) : (
          <div className={style.relatedImages_wrapper}>
            <div className={style.relatedImages_title}>[相关图片]</div>
            <div className="relatedImages">
              {relatedImages_edit &&
                relatedImages_edit.map((item, index) => {
                  return (
                    <div
                      key={index}
                      style={{ display: "inline-block", position: "relative" }}
                    >
                      <img
                        src={item.relatedImageUrl}
                        alt=""
                        className={style.relatedImage_edit}
                      />
                      <img src={closeIcon} alt="" className={style.closeIcon} />
                    </div>
                  );
                })}
              <img
                src={addIcon}
                alt=""
                className={style.relatedImage_edit}
                onClick={() => uploadImages()}
              />
            </div>
          </div>
        )}
      </div>
      <button
        className={proFile ? style.btn_save_edit : style.btn_save}
        onClick={() => onSave()}
      >
        保存
      </button>
    </div>
  );
};

export default Index;
